package com.lenovo.newsapp.activity;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.adobe.mobile.Analytics;
import com.adobe.mobile.Config;
import com.lenovo.newsapp.R;
import com.lenovo.newsapp.adapter.CommentListAdapter;
import com.lenovo.newsapp.model.Comment;
import com.lenovo.newsapp.parser.InfoJSONParser;
import com.lenovo.newsapp.util.Const;
import com.lenovo.newsapp.util.PreferenceUtil;
import com.lenovo.newsapp.util.ThreadPool;
import com.lenovo.newsapp.view.MyPullToRefreshListView;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnFooterLoadListener;
import com.lenovo.newsapp.view.MyPullToRefreshListView.OnHeaderLoadListener;
import com.worklight.wlclient.api.WLClient;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLProcedureInvocationData;
import com.worklight.wlclient.api.WLResponse;
import com.worklight.wlclient.api.WLResponseListener;

public class CommentListActivity extends BaseActivity implements
		OnClickListener, OnHeaderLoadListener, OnFooterLoadListener {

	private Button btn_send;
	private EditText et_comment;
	private ProgressBar progressBar;
	private MyPullToRefreshListView listview;
	private CommentListAdapter myListAdapter;
	// private View rootView;
	private int pageNo;
	boolean success = true;
	boolean canLoadMore = true;
	private final Handler handler = new Handler();
	private ArrayList<Comment> resultList = new ArrayList<Comment>();
	
	int newsId;
	
	private InputMethodManager imm;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		newsId = getIntent().getIntExtra("newsId", 0);
		setContentView(R.layout.activity_comment_list);
		listview = (MyPullToRefreshListView) findViewById(R.id.comment_list);
		et_comment = (EditText) findViewById(R.id.et_comment);
		btn_send = (Button) findViewById(R.id.btn_send);
		btn_send.setOnClickListener(this);
		
		imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		Analytics.trackState("CommentListActivity", null);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Config.pauseCollectingLifecycleData();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		Config.collectLifecycleData();
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		pageNo = 1;
		loadData(Const.INIT_FLAG);
	}

	private void loadMoreListView() {
		myListAdapter.appendOlder(resultList);
		listview.onFooterLoadComplete();
	}

	private void refreshListView() {
		myListAdapter.refreshData(resultList);
		listview.onHeaderLoadComplete();
	}

	@Override
	public void onFooterLoad() {

		if (null != resultList && resultList.size() > 0) {
			pageNo++;
			loadData(Const.LOAD_MORE_FLAG);
		} else {
			showShortToast(R.string.load_no_more_message);
			listview.onFooterLoadComplete();
		}
	}

	/**
	 * 加载列表
	 */
	private void loadData(final int flag) {
		if (flag == Const.INIT_FLAG) {
			showLoadProgressBar();
		}
		ThreadPool.execute(new Runnable() {

			@Override
			public void run() {
				try {
					resultList = InfoJSONParser.getCommentList(newsId,pageNo);
					Log.v(Const.DEBUG, "resultList" + resultList.size());
					canLoadMore = (resultList.size() == Const.PAGE_SIZE);
					Log.v(Const.DEBUG, "canLoadMore" + canLoadMore);
					success = true;
				} catch (Exception e) {
					success = false;
					e.printStackTrace();
				}

				handler.post(new Runnable() {

					@Override
					public void run() {
						if (success) {
							switch (flag) {
							case Const.INIT_FLAG:
								setUpListViews();
								break;
							case Const.LOAD_MORE_FLAG:
								loadMoreListView();
								break;
							case Const.REFRESH_FLAG:
								refreshListView();
							default:
								break;
							}
						} else {
							showShortToast(R.string.toast_err_download);
						}

						listview.onHeaderLoadComplete();
						listview.setCanLoadFooter(canLoadMore);
						hideLoadProgressBar();
					}

				});
			}
		});
	}

	@Override
	public void onHeaderLoad() {
		pageNo = 1;
		loadData(Const.REFRESH_FLAG);
	}

	private void setUpListViews() {
		Log.v(Const.DEBUG, "r.resultList.size() " + resultList.size());
		if (null != resultList && resultList.size() > 0) {
			myListAdapter = new CommentListAdapter(this, resultList);
			listview.setAdapter(myListAdapter);
			listview.setOnHeaderLoadListener(this);
			listview.setOnFooterLoadListener(this);
			// listOnclicklistener listener = new listOnclicklistener();
			// listview.setOnItemClickListener(listener);

		}
	}

	/**
	 * 首页list点击事件，根据类型进入不同页面
	 * 
	 * @author Geoffrey
	 * 
	 */
	// class listOnclicklistener implements OnItemClickListener {
	//
	// @Override
	// public void onItemClick(AdapterView<?> arg0, View arg1, int position,
	// long arg3) {
	// HomeNews info = (HomeNews) listview.getItemAtPosition(position);
	// Intent intent = new Intent(main, NewsDetailImgActivity.class);
	//
	// startActivity(intent);
	// }
	// }
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		int id = v.getId();
		// 发送按钮
		if (id == R.id.btn_send) {
			if (et_comment.getText().toString().equals("")) {
				Log.v("comment", "内容不能为空");
				Toast.makeText(CommentListActivity.this, "输入内容不能为空",
						Toast.LENGTH_LONG).show();
			} else {
				Log.v("comment", "输入内容为" + et_comment.getText().toString());

				showLoadProgressBar();
				String adapterName = "NewsAppAdapter";
				String procedureName = "commentsNews";
				TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); 
				String deviceId = tm.getDeviceId();
				
				WLProcedureInvocationData invocationData = new WLProcedureInvocationData(
						adapterName, procedureName);
				Object[] parameters = new Object[] {newsId+"", et_comment.getText().toString(), "guxl4"};
				invocationData.setParameters(parameters);

				LoginActivity.client = WLClient.getInstance();
				LoginActivity.client.invokeProcedure(invocationData,
						new WLResponseListener() {

							public void onSuccess(WLResponse response) {
								final JSONObject jsonObj = response.getResponseJSON();
								Log.v(Const.DEBUG, "onSuccess--dataJson = " + jsonObj);
								handler.post(new Runnable() {

									@Override
									public void run() {
										try {
											Toast.makeText(CommentListActivity.this, jsonObj.getString("msg"),
													Toast.LENGTH_LONG).show();
										} catch (JSONException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										loadData(2);
//										refreshListView();
										hideLoadProgressBar();
									}

								});

							}

							public void onFailure(WLFailResponse response) {
								Log.v(Const.DEBUG, "onFailure--dataJson = " + response);
//								String responseText = response.getResponseText();
								handler.post(new Runnable() {

									@Override
									public void run() {
										hideLoadProgressBar();
									}

								});
							}

						}, null);

			
				et_comment.setText("");
				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
			}

		}
		// else {
		// }
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == android.R.id.home) {
			finishWithAnimation();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}
}
